package it.sebsibenal.server.controller;

import it.sebsibenal.server.dao.UserAccessDAO;
import it.sebsibenal.server.dao.UserDAO;
import it.sebsibenal.shared.UserAccess;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class AccessController extends AbstractController {

	private static final Logger logger = Logger.getLogger(AccessController.class);
	
	private UserAccessDAO userAccessDAO;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		
		String username = "guest";
		String email = "guest";
		String logoutUrl = "";
		String thisURL = request.getRequestURI();
		if (request.getUserPrincipal()!=null) {
			username = userService.getCurrentUser().getNickname();
			logoutUrl = userService.createLogoutURL(thisURL);
			email = userService.getCurrentUser().getEmail();
			UserAccess ua = new UserAccess();
			ua.setEmail(email);
			ua.setTimestamp(new Date());
			userAccessDAO.insert(ua);
		} 
		ModelAndView mav = new ModelAndView("index");
		mav.addObject("username", username);
		mav.addObject("email", email);		
		mav.addObject("logoutUrl", logoutUrl);
		return mav;
	}

	public void setUserAccessDAO(UserAccessDAO userAccessDAO) {
		this.userAccessDAO = userAccessDAO;
	}

}
